package de.rj.urwalking.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import de.rj.urwalking.R;
import de.rj.urwalking.config.Config;

/**
 * http://android-er.blogspot.in/2010/08/simple-compass-sensormanager-and.html
 * 
 * 
 */

public class CompassView extends View {

	private float direction = 0;
	private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
	private boolean firstDraw;
	private boolean isScaled = false;
	private Context context;
	private Bitmap mCompassRose;

	public CompassView(Context context) {
		super(context);
		this.context = context;
		init();
	}

	public CompassView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		init();
	}

	public CompassView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		init();
	}

	private void init() {

		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(3);
		paint.setColor(0xAA000000);
		paint.setTextSize(30);

		mCompassRose = BitmapFactory.decodeResource(context.getResources(), R.drawable.compass);
		firstDraw = true;
		invalidate();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
	}

	@Override
	protected void onDraw(Canvas canvas) {

		int width = getMeasuredWidth();
		int height = getMeasuredHeight();

		if (!isScaled) {
			mCompassRose = Bitmap.createScaledBitmap(mCompassRose, width, height, false);
			isScaled = true;
		}

		if (!firstDraw) {

			Matrix transform = new Matrix();
			transform.preRotate(-(float) (direction * 180 / Math.PI), width / 2, height / 2);
			canvas.drawBitmap(mCompassRose, transform, null);
		}
		// Log.d(Config.TAG, "Drawing compass, angle " + direction);
	}

	public void updateDirection(float dir) {
		firstDraw = false;
		direction = dir;
		invalidate();
	}

}